import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http'
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core'
import { AdConfirmService } from 'monk-design/confirm'
import { AdHttpService } from 'monk-design/http'
import { AdResourceService } from 'monk-design/resource'
import { NzNotificationModule } from 'ng-zorro-antd/notification'
import { InjectorModule } from './injector.module'
import { AD_RESOURCE_URL, AD_AUTH, AdAuth } from 'monk-design/config'

export interface AdCoreConfig {
  /**
   * 资源前缀工厂函数
   * @returns {string}
   */
  resourcePrefixFactory: () => string

  /**
   * 权限鉴权
   */
  auth?: AdAuth
}

@NgModule({
  imports: [InjectorModule, HttpClientModule, HttpClientJsonpModule, NzNotificationModule],
})
export class AdCoreModule {
  constructor(@Optional() @SkipSelf() parentModule: AdCoreModule) {
    if (parentModule) {
      throw new Error('AdCoreModule is already loaded. Import it in the AppModule only')
    }
  }
  /**
   *
   * @param config
   * @returns
   */
  static forRoot(config: AdCoreConfig): ModuleWithProviders<AdCoreModule> {
    return {
      ngModule: AdCoreModule,
      providers: [
        AdResourceService,
        AdConfirmService,
        AdHttpService,
        {
          provide: AD_RESOURCE_URL,
          useFactory: config.resourcePrefixFactory,
        },
        {
          provide: AD_AUTH,
          useValue: config.auth || ((auth: string) => !auth),
        },
      ],
    }
  }
}
